import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/*
    创建一个线程的4中方法:
        1.继承Thread类
        2.实现Runnable接口
        3.用线程池创建
        4.实现Callable<V>接口
 */
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        FutureTask<Integer> futureTask=new FutureTask<>(new MyThread());
        new Thread(futureTask,"A").start();
        //当有多个线程想执行同一个futureTask时，先进去的线程会去做，后面的线程不会进去
        new Thread(futureTask,"B").start();
        int num=100;
        //futureTask.isDone():当callable线程运行完毕后返回true
        while (!futureTask.isDone()){

        }
        //从callable线程获取结果，如果callable线程没有执行完，那么将会进入阻塞状态
        int result = futureTask.get();

        System.out.println("result获取成功");
        System.out.println(result+num);
    }
}
class MyThread implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("开启一个新的线程"+Thread.currentThread().getName());
        Thread.sleep(2000);
        return 1024;
    }
}
